#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 128

char buf[N + 1];

int Judge(char *str, int start) // 判断3个连续字符是否为重复字符
{
    if (str[start + 0] == str[start + 1] && str[start + 1] == str[start + 2])
        return 1;
    return 0;
}
int main(int argc, char *argv[])
{
    if (argc == 1)
    {
        printf("ZIP: file1 file2 ...\n");
        exit(1);
    }
    FILE *fp2 = fopen("./test", "w");
    for (int i = 1; i < argc; ++i)
    {
        FILE *fp = fopen(argv[i], "r");
        if (fp == NULL)
        {
            perror("ZIP");
            fclose(fp2);
            exit(1);
        }
        while (fgets(buf, N, fp) != NULL)
        {
            int start = 0, end = strlen(buf);
            while (start < end)
            {
                if (start + 2 >= end || Judge(buf, start) == 0) // 这是不重复的字符处理
                {
                    //printf("进入不重复字符处理\n");
                    int count = 0;
                    int index = start;
                    while (index + 2 < end && Judge(buf, index) == 0)
                    {
                        ++count;
                        ++index;
                    }
                    if (index + 2 >= end)
                        count += 2;
                    unsigned char ch = 0x00;
                    ch |= count;
                    //printf("%d\n",count);
                    fwrite(&ch, sizeof(char), 1, fp2);
                    fwrite(buf + start, count, 1, fp2);
                    start += count;
                }
                else // 重复字符处理
                {
                    //printf("进入重复字符处理\n");
                    int index = start+3;
                    while(index < end && buf[index] == buf[start])
                        ++index;
                    unsigned char ch = 0x80;
                    ch |= (index-start);
                    //printf("%d\n",index-start);
                    fwrite(&ch,1,1,fp2);
                    fwrite(buf+start,1,1,fp2);
                    start = index;
                }
            }
        }
        fclose(fp);
    }
    fclose(fp2);
    return 0;
}